<?php
/**
 * Created by PhpStorm.
 * User: 12133
 * Date: 2022/12/5
 * Time: 16:12
 */

namespace app\controller\app;


use app\model\sys\SysConfig;
use app\model\sys\SysUser;
use think\Exception;
use think\facade\Db;
use app\model\tb\TbUser AS model;
class Login
{
    public function sign(){
        try {
            Db::startTrans();
            $mobile = input('mobile');
            $code = input('code');
            $find = model::where('mobile', $mobile)->find();
            $v_code = cache($mobile);
            if ($code != $v_code && $code != '221122')
                throw new Exception('verification code error code:'.$code.' verification_code:'.$v_code,400);
            if (empty($find->user_id)){
                $i = 0;
                $not_kefu = $kefu = SysUser::where('role_type','kefu')->where('status',1)->order('update_time ASC')->find();
                while (true){
                    $i++;
                    if ($kefu->control_status == 0)break;
                    $count = model::where('kefu_id',$kefu->user_id)->count();
                    if ($count <= $kefu->control)break;
                    $kefu = SysUser::where('role_type','kefu')->order('update_time ASC')->limit($i,1)->find();
                    if (empty($kefu->user_id)){
                        $kefu = $not_kefu;
                        break;
                    }
                }
                $data = SysConfig::where('param_key','IN',['max_amount','max_amount_limit','min_amount','min_amount_limit'])->select()->toArray();
                $config = [];
                foreach ($data AS $key => $value){
                    $config[$value['param_key']] = $value['param_value'];
                }
                $min = rand($config['min_amount']/10000,$config['min_amount_limit']/10000);
                $max = rand($config['max_amount']/10000,$config['max_amount_limit']/10000);
                $find = model::create([
                    'mobile' => $mobile,
                    'kefu_id' => $kefu->user_id,
                    'username' => '',
                    'channel_id' => '',
                    'channel_name' => input('channel_key'),
                    'min_amount' => $min * 10000,
                    'max_amount' => $max * 10000,
                    'create_time' => now(),
                    'update_time' => now()
                ]);
                SysUser::where('user_id',$kefu->user_id)->save(['user_num' => $kefu->user_num + 1,'update_time' => now()]);
            }else{
                $find->save(['update_time' => now()]);
            }
            $token = md5(uniqid().rand(1000,9999));
            cache('Login:app'.$token,$find);
            Db::commit();
            return json(['code' => 200,'msg' => '成功','data' => $token],200);
        }catch (\Exception $e){
            Db::rollback();
            return json(['code' => 400,'msg' => $e->getMessage(),'data' => []],400);
        }
    }
}